/**
 * Created by cchen on 2015/4/28.
 */

var serviceCount = mongoose.model('backoffice_serviceCount');
var aUser=mongoose.model('backoffice_adminusers');

var User = mongoose.model('user');
var Community = mongoose.model('community');

var async = require('async');
var toolUtil = require('../../common/utils/toolUtil');


exports.createServiceUser=function(callback){
    async.waterfall([
        function(innerCallback){
            exports.getServiceCount(innerCallback);
        },
        function(result, innerCallback){
            if(result.length>0) {
                var obj=result[0];
                console.log(1);
                exports.updateServiceCount(obj._id,obj.count + 1, function(err,o){
                    if(err)
                    {
                        innerCallback(err,null);
                    }
                    innerCallback(null, obj);
                });
            }else {
                innerCallback("error",null);
            }
        },
        function(result, innerCallback){
            console.log(2);
            var mobilePhone =result.count;
            var args = {
                data: {
                    username: mobilePhone + '',
                    password: mobilePhone + ''
                },
                headers: {"Content-Type": "application/json"}
            };
            exports.registerHuanxinAccount(args, function(data,res){
                innerCallback(null,result);
            },function(err){
                innerCallback(err,null);
            })

        },
        function(result, innerCallback){
            console.log(3);
            exports.addServiceUserAccount(result.count,'service',function(err,obj){
                if(err){
                    callback(err,null);
                }
                callback(null,obj);
            });
        }
    ], function (err, result) {
        callback(err,null);;
    })


}

exports.getServiceCount=function(callback){
    serviceCount.find({},callback);
}

exports.updateServiceCount=function(id,count,callback){
    serviceCount.update({"_id":id}, {count: count},callback);
}

exports.registerHuanxinAccount=function(data,successCB,errorCB){
    restClient.post("http://a1.easemob.com/66xiaoqu/"+huanxinEnv+"/users", data,successCB).on('error',errorCB)
}

exports.addServiceUserAccount=function(mobilePhone,userType,callback){
    var temp = new User();
    temp.mobilePhone = mobilePhone + '';
    temp.userPassword = '670b14728ad9902aecba32e22fa4f6bd';   //密码：000000
    temp.huanxinUserName = mobilePhone + '';
    temp.userType=userType;
    temp.nickName="小6客服";
    temp.images=[{imageURL:"/group1/M00/00/03/rB75BFTZeeWAQScdAABIYpzs0fE223.png"}];
    temp.save(callback);
}

exports.chainUpServicAndUser=function(serviceId,userId,callback) {
    exports.isExist(serviceId, function (err, result) {
        console.log(4);
            if(result!==null||!result.appuser||result.appuser===null) {
                result.appuser = userId;
                result.save(callback);
            }else{
                callback({message: "Error On binding User"}, null);
            }
    });
}
exports.removeServiceChain=function(serviceId,callback)
{
    exports.isExist(serviceId,function(err,result)
    {
        result.appuser=undefined;
        result.save(callback);
     });
    //userServiceChain.findOneAndRemove({serviceId:serviceId},callback);
}

exports.isExist=function(serviceId,callback)
{
    aUser.findOne({_id:serviceId},function(err,result){
         callback(err,result);
    });
}



exports.getAllCommunity=function(callback)
{
     Community.find({},callback);
}

exports.getAllOccupiedCommunity=function(callback)
{
    //aUser.find({"role":"Service"},callback);
    aUser.find({"role":"Service"},{communities:1},callback);
}

exports.getAvailableCommunities=function(callback){
    async.waterfall([
        function(innerCallback){
            exports.getAllOccupiedCommunity(function(err,list2){
                console.log(list2)
                var empt=[];
                list2.forEach(function(obj,index,array){
                    if(obj.communities)
                    {
                        obj.communities.forEach(function(comId,index,arr){
                                empt.push(comId+"");
                        })

                    }
                });
                console.log(empt);
                //one community can have more customer,  service use empty array instead without checking
                Community.find({"_id":{'$nin':[]}},function(err,result){
                    if(err){
                        callback(err,null);
                    }
                    else{
                        callback(null,result);
                    }
                });
            })
        }
        ],
        function(err, result){
            callback(err,result);

    });
}

exports.getAllUnbindServiceUser=function(callback){
    aUser.find({role:{"$in":["Service","Operation"]}},{appuser:1},function(err,result){
        if(err){
            callback(err,null);
        }
        var empty=[]
        result.forEach(function(obj,index,array){
            empty.push(obj.appuser);
        });
        User.find({userType:"service","_id":{'$nin':empty}},{_id:1, mobilePhone:1},function(err,result){
            callback(err,result);
        })
    })

}

exports.getBindedServiceUser=function(serviceId,callback){
    aUser.findOne({"_id":serviceId},{},function(err,result){
        callback(err,result);
    });

}

exports.updateSignedService=function(userList,callback) {
async.each(userList,function(user,innerCallback){
    aUser.findOne({"_id":user._id},{},function(err,result){
        console.log(result);
        result.signed=user.signed;
        if(user.signed){
            toolUtil.pushServiceId(result.communities,result.appuser.mobilePhone);
        }
        result.save();
        innerCallback();
    }).populate("appuser","mobilePhone");

},function(err){
    callback(err,{"status":"ok"});
});

}
